/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 17655
 * Date: 2025-09-16
 * Time: 12:54
 */
// 三个线程交替打印
public class test3 {
    // 最终数字
    private static final int FINAL_NUMBER = 200;
    // 锁
    private static Object lock = new Object();
    // 当前数字
    private static int currentNum = 1;

    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            while (currentNum<FINAL_NUMBER) {
                synchronized (lock) {
                    while (currentNum % 3 != 1) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println("t1:" + currentNum);
                    currentNum++;
                    lock.notifyAll();
                }
            }
        });

        Thread t2 = new Thread(()->{
            while (currentNum<FINAL_NUMBER){
                synchronized (lock){
                    while (currentNum%3!=2){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println("t2:"+currentNum);
                    currentNum++;
                    lock.notifyAll();
                }
            }
        });

        Thread t3 = new Thread(()-> {
            while (currentNum < FINAL_NUMBER) {
                synchronized (lock) {
                    while (currentNum % 3 != 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.println("t3:" + currentNum);
                    currentNum++;
                    lock.notifyAll();
                }
            }
        });
        t1.start();
        t2.start();
        t3.start();
    }
}
